<script setup>
  /** Handles a search filters block bound with URL params
   *
   * This is a bidirectional bind between filters and URL:
   *
   * - filters inputs will be initialized with URL data
   * - submitting the <form> will navigate to the current view with current filters as URL query
   * - if initialFilters changes, filters will be set to initialFilters value
   */

  import Input from '@/components/forms/Input.vue'
  import Select from '@/components/forms/Select.vue'
  import CollapsibleSearchFilters
    from '@/components/CollapsibleSearchFilters.vue'
  import { useCompanyConfigStore } from '@/stores/company'
  import { useRoute, useRouter } from 'vue-router'

  const filtersFormConfigUrl = '/api/v1/companies.geojson?form_config=1'

  const router = useRouter()
  const route = useRoute()
  const formConfigStore = useCompanyConfigStore()

  const navigateTo = (filters) => {
    router.push({ path: '/companies_map', query: filters })
  }

  formConfigStore.setUrl(filtersFormConfigUrl)
  await formConfigStore.loadConfig()
  const activitiesOptions = formConfigStore.getOptions('activities')
</script>

<template>
  <CollapsibleSearchFilters
    title='Recherche'
    @applyFilters='navigateTo'
    :initialFilters='route.query'
  >
    <Input
      label='Nom, enseigne, activité' name='search'
      :value='route.query.search'
    />
    <Select
      label="Type d'activité" name='activity_id'
      :options='activitiesOptions'
      :value='route.query.activity_id'
      add-default
      :default-option="{ id: '', label: '- Tous les types d\'activité -' }"
    />
    <Input
      label='Code postal' name='postcode'
      :value='route.query.postcode'
    />
  </CollapsibleSearchFilters>
</template>
